package com.cheng.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

//UDP多线程在线咨询
public class TalkSend implements Runnable{
    DatagramSocket socket =null;
    DatagramPacket packet = null;
    BufferedReader reader = null;

    //定义发送地址和接收地址
    private int sendPort;
    private int receivePort;
    private String receiveIp;
    String data = null;

    //初始化参数放入构造器
    public TalkSend(int sendPort, int receivePort, String receiveIp) {
        this.sendPort = sendPort;
        this.receivePort = receivePort;
        this.receiveIp = receiveIp;
        try {
            socket = new DatagramSocket(sendPort);//建立Socket连接
            reader = new BufferedReader(new InputStreamReader(System.in));// 用System.in从控制台得到数据
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        while(true){
            //把从数据台得到的消息读取出来
            try {
                data = reader.readLine();
                byte[] dataBytes = data.getBytes();
                //                                        要发送的数据       数据的长度             接收数据的地址
                DatagramPacket packet = new DatagramPacket(dataBytes,0,dataBytes.length,new InetSocketAddress(this.receiveIp,this.receivePort ));
                //用DatagramSocket发送数据包
                socket.send(packet);
                byte[] data1 = packet.getData();
                String sendData = new String(data1,0,data1.length);
                if(dataBytes.equals("再见")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //关闭连接
        socket.close();
    }
}
